package com.ujs.edu.medicine.controller;

import com.auth0.jwt.JWT;
import com.ujs.edu.medicine.dao.TableChatMesMapper;
import com.ujs.edu.medicine.dao.YunjiayiMessageMapper;
import com.ujs.edu.medicine.dao.YunjiayiPrescriptionMapper;
import com.ujs.edu.medicine.dao.YunjiayiUserMapper;
import com.ujs.edu.medicine.dataobject.*;
import com.ujs.edu.medicine.util.DateFormate;
import com.ujs.edu.medicine.util.Result;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;






import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/prescription")
public class PrescriptionController {
    @Autowired
    private  YunjiayiPrescriptionMapper  yunjiayiPrescriptionMapper;
    @Autowired
    private YunjiayiUserMapper yunjiayiUserMapper;
    @Autowired
    private TableChatMesMapper tableChatMesMapper;
    @Autowired
    private YunjiayiMessageMapper yunjiayiMessageMapper;
    @Autowired
    private HttpServletRequest request;
    private String gettoken() {
        return request.getHeader("Authorization");
    }

    /*增加处方*/
    @PostMapping()
    public Result PostPrescription(@RequestBody Map<String,String>map) {
        Result result = new Result();
        String token = gettoken();
        int myuserid=0;
        try {
            myuserid= JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("没有登陆，请登陆");
            return result;
        }

        YunjiayiPrescription prescription = new  YunjiayiPrescription();
        prescription.setDoctorid(myuserid);
        prescription.setPatientid(Integer.parseInt(map.get("patientID")));
        prescription.setDecription(map.get("description"));
        prescription.setMedicine(map.get("medicine"));
        prescription.setPrescriptionstatus(map.get("prescriptionstatus"));//0是不允许开处方，1是为开处方，2是已开处方

        int tip =  yunjiayiPrescriptionMapper.insert(prescription );

        List<TableChatMes> tableChatMes1=tableChatMesMapper.selectByFromUserIDOrTouserId(myuserid);

        for (TableChatMes tableChatMes2:tableChatMes1){
            tableChatMes2.setPrescriptionid(prescription.getPrescriptionid());
            tableChatMesMapper.updateByPrimaryKey(tableChatMes2);
        }


        List<YunjiayiMessage> message=yunjiayiMessageMapper.selectByUSer(myuserid);

        for (YunjiayiMessage message1:message){
            message1.setPrescriptionid(prescription.getPrescriptionid());

            yunjiayiMessageMapper.updateByPrimaryKey(message1);
        }

        result.setCode(tip==0?1:0);
        result.setMessage(tip == 0 ? "增加成功" : "增加失败");
        return result;
    }

    /*获取处方列表*/
   @GetMapping(path="/list")
   public Result GetPrescription(@RequestParam(value = "userID", required = false) Integer userID,
                                 @RequestParam(value = "page", required = false) Integer page) {
       Result result = new Result();
       List<YunjiayiPrescription> Prescriptions = new ArrayList<>();
       Author author=new Author();
       if (userID != null) {
           Prescriptions = yunjiayiPrescriptionMapper.getPrescriptionById(userID);
       } else if (page != null) {
           Integer startIndex=(page-1)*10+1;
           Integer pageSize=10;
           Prescriptions = yunjiayiPrescriptionMapper.selectLimit(startIndex,pageSize);
           System.out.println(Prescriptions);
       }
       if(Prescriptions!=null) {
           JSONObject[] JSONObjectArry = new JSONObject[ Prescriptions .size()];
           for (int i = 0; i < Prescriptions.size(); i++) {
               JSONObjectArry[i] = new JSONObject();
               author = yunjiayiUserMapper.selectAuthorByPrimaryKey(Prescriptions.get(i).getDoctorid());
               JSONObjectArry[i].put("id", Prescriptions.get(i).getPrescriptionid());
               JSONObjectArry[i].put("createTime",Prescriptions.get(i).getCreatime());
               JSONObjectArry[i].put("abstract", Prescriptions.get(i).getDecription());
               JSONObjectArry[i].put("author", author);
           }
           result.setCode(0);
           result.setData(JSONObjectArry);
           result.setMessage("获取成功");
       }else{
           result.setCode(1);
           result.setMessage("获取成功");
       }
           return result;
   }

   /*获取处方具体信息*/
    @GetMapping()
    public Result GetPrescription(@RequestParam(value = "id", required = true) Integer id) {
        Result result = new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您未登陆,请登陆");
            return result;
        }

        YunjiayiPrescription  Prescription = yunjiayiPrescriptionMapper.selectByPrimaryKey(id);

        YunjiayiUser  doctor= yunjiayiUserMapper.selectByPrimaryKey(Prescription.getDoctorid());
        JSONObject json= new JSONObject();

        if(Prescription!=null) {
            YunjiayiUser  patient= yunjiayiUserMapper.selectByPrimaryKey(Prescription.getPatientid());

            json.put("sex",patient.getSex());
            json.put("age", patient.getAge()); // 患者年龄
            json.put("realname",patient.getRealname()); // 患者真实姓名
            json.put("patientName",doctor.getRealname()); // 医生姓名
            json.put("createTime", Prescription.getCreatime());
            json.put("decription", Prescription.getDecription());
            json.put("medicine", Prescription.getMedicine());

            result.setCode(0);
            result.setData(json);
            result.setMessage("获取成功");
        }
        else
        {
            result.setCode(1);
            result.setMessage("获取失败");
        }
        return result;
    }


    public static String getStringDateShort(Date currentTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }
}
